import { useEffect, memo, useMemo, useState } from 'react'
import { useRequest } from 'ahooks'
import { OrgSettle, OrgSettleStatus, queryOrgSettleListOfStation, OrgSettleOfStation } from './services'
import { Button, Card, Descriptions, Space, Table, Tag } from 'antd'
import { styled, history } from '@umijs/max'
import dayjs from 'dayjs'
import { PAGINATION_CONFIG } from '@/constants'
import { ColumnsType } from 'antd/es/table'
import { jump2target } from '@/utils/common'

const Container = styled.div`
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 24px;

  .ant-descriptions-item-label {
    align-items: center !important;
  }
`

const dateFormat = (yyyymmdd: string) => {
  return `${yyyymmdd.substring(0, 4)}-${yyyymmdd.substring(4,6)}-${yyyymmdd.substring(6)}`
}

const OrgSettleDetail: React.FC<RoutePageProps> = props => {
  const [data, setData] = useState<OrgSettle>()
  const [settleId, setSettleId] = useState<string>()
  const [pagination, setPagination] = useState<PaginationParams>({pageNum: 1, pageSize: 10})
  const { data: list, loading, runAsync } = useRequest(queryOrgSettleListOfStation, {manual: true})

  const calcValue = useMemo(() => {
    const _result: any = {}
    if (data) {
      switch (data.status) {
        case OrgSettleStatus.待打款: 
        case OrgSettleStatus['待打款(已修改资料)']: _result.status = <Tag color="processing">待打款</Tag>; break
        case OrgSettleStatus.已打款: _result.status = <Tag color="success">已打款</Tag>; break
        case OrgSettleStatus.打款失败: _result.status = <Tag color="error">打款失败</Tag>; break
      }
      _result.settleRange = `${dayjs(data.beginDay).format('YYYY.MM.DD')}-${dayjs(data.endDay).format('YYYY.MM.DD')}`
      const _chargeMoney = parseFloat((data.chargeElectricMoney + data.chargeServiceMoney).toFixed(2))
      _result.chargeMoney = _chargeMoney.toLocaleString()
    }
    return _result
  }, [data])

  const jump2chargeSettlePage = (record: OrgSettleOfStation) => {
    sessionStorage.setItem('_searchParams_settleDetail', JSON.stringify({
      stationId: record.stationId,
      stationName: record.stationName,
      // settleId: data!.settleId,
      beginDay: data!.beginDay,
      endDay: data!.endDay || '',
    }))
    jump2target(`/moneySettle/chargeOrderSettle?sKey=_searchParams_settleDetail___${new Date().getTime()}`, {needRefresh: true})
  }

  const jump2occupySettlePage = (record: OrgSettleOfStation) => {
    sessionStorage.setItem('_searchParams_settleDetail', JSON.stringify({
      stationId: record.stationId,
      stationName: record.stationName,
      // settleId: data!.settleId,
      beginDay: data!.beginDay,
      endDay: data!.endDay || '',
    }))
    jump2target(`/moneySettle/occupySe?sKey=_searchParams_settleDetail___${new Date().getTime()}`, {needRefresh: true})
  }

  const columns: ColumnsType<OrgSettleOfStation> = [
    {
      title: '场站名称',
      dataIndex: 'stationName',
      width: 100,
    },
    {
      title: '结算周期',
      dataIndex: 'beginDay',
      width: 180,
      render: (val, record) => {
        if (!val) return '--'
        if (!record.endDay) return `${dateFormat(val)}至 --`
        return `${dateFormat(val)}至${dateFormat(record.endDay)}`
      }
    },
    {
      title: '结算电量(度)',
      dataIndex: 'power',
      width: 100,
    },
    {
      title: '充电电费(元)',
      dataIndex: 'chargeElectricMoney',
      width: 120,
    },
    {
      title: '充电服务费(元)',
      dataIndex: 'chargeServiceMoney',
      width: 140,
    },
    {
      title: '充电结算金额(元)',
      dataIndex: 'chargeMoney',
      width: 140,
    },
    {
      title: '占位费(元)',
      dataIndex: 'occupyMoney',
      width: 120,
    },
    {
      title: '通道费(元)',
      dataIndex: 'pathMoney',
      width: 120,
    },
    {
      title: '操作',
      key: 'operation',
      width: 200,
      fixed: 'right',
      render: (_, record) => {
        return <Space>
          <a onClick={() => jump2chargeSettlePage(record)}>充电结算明细</a>
          <a onClick={() => jump2occupySettlePage(record)}>占用结算明细</a>
        </Space>
      }
    },
  ]

  useEffect(() => {
    if (settleId) {
      runAsync({
        ...pagination,
        settleId,
      })
    }
  }, [pagination])

  useEffect(() => {
    if (props.params.sKey) {
      const _params = sessionStorage.getItem(props.params.sKey.split('___')[0])
      if (_params) {
        const _data = JSON.parse(_params)
        setData(_data)
        runAsync({
          ...pagination,
          settleId: _data.settleId,
        })
        setSettleId(_data.settleId)
      }
    }
  }, [props.params.sKey])

  return (
    <Container>
      <Card title={<Space>
        <div>{`结算单ID: ${data?.id}`}</div>
        {calcValue.status || ''}
      </Space>}>
        <Descriptions column={3}>
          <Descriptions.Item label='结算周期'>{calcValue.settleRange || '--'}</Descriptions.Item>
          <Descriptions.Item label='结算企业'>{data?.orgName || '--'}</Descriptions.Item>
          <Descriptions.Item label='提交时间'>{data?.createTime ? dayjs(data.createTime).format('YYYY-MM-DD HH:mm:ss') : '--'}</Descriptions.Item>
        </Descriptions>
      </Card>
      <Card title='结算金额'>
        <Descriptions column={3}>
          <Descriptions.Item label='充电结算总金额(元)'>{calcValue.chargeMoney || '--'}</Descriptions.Item>
          <Descriptions.Item label='占用结算总金额(元)'>{data?.occupyMoney || '--'}</Descriptions.Item>
          <Descriptions.Item label='结算电费(元)'>{data?.chargeElectricMoney || '--'}</Descriptions.Item>
          <Descriptions.Item label='结算服务费(元)'>{data?.chargeServiceMoney || '--'}</Descriptions.Item>
          <Descriptions.Item label='通道费(元)'>{data?.pathMoney || '--'}</Descriptions.Item>
          <Descriptions.Item label='结算电量(元)'>{data?.power || '--'}</Descriptions.Item>
          <Descriptions.Item label='充电订单税费(元)'>{data?.chargeInvoiceMoney || '--'}</Descriptions.Item>
          <Descriptions.Item label='占用订单税费(元)'>{data?.occupyInvoiceMoney || '--'}</Descriptions.Item>
        </Descriptions>
      </Card>
      <Card title='电站费用列表' extra={<Button onClick={() => setPagination({...pagination, pageNum: 1})} type='primary'>查询</Button>}>
        <Table<OrgSettleOfStation>
          rowKey='stationId'
          loading={loading}
          dataSource={list?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            pageSize: 10,
            showSizeChanger: false,
            total: list?.totalCount || 0,
            onChange: (page, pageSize) => {
              setPagination({
                pageSize,
                pageNum: page === pagination.pageNum ? 1 : page,
              })
            }
          }}
        />
      </Card>
    </Container>
  )
}

export default memo(OrgSettleDetail)
